package com.wk.springboot.ttl.context;

import com.alibaba.ttl.TransmittableThreadLocal;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class InheritableThreadLocalExample {

    private static InheritableThreadLocal<String> inheritableThreadLocal = new InheritableThreadLocal<>();
    private static TransmittableThreadLocal<String> transmittableThreadLocal = new TransmittableThreadLocal<>();

    public static void main(String[] args) throws InterruptedException {
        inheritableThreadLocal.set("Parent Thread Value");
        transmittableThreadLocal.set("Parent Thread Value");

        ExecutorService executorService = Executors.newFixedThreadPool(2);
        
        // 提交第一个任务
        executorService.submit(() -> {
            System.out.println("Task 1 - Thread [" + Thread.currentThread().getName() + "] InheritableThreadLocal Value: " + inheritableThreadLocal.get());
            System.out.println("Task 1 - Thread [" + Thread.currentThread().getName() + "] transmittableThreadLocal Value: " + transmittableThreadLocal.get());
        });
        // 修改父线程中的 InheritableThreadLocal 值
        inheritableThreadLocal.set("Updated Parent Thread Value");
        transmittableThreadLocal.set("Parent Thread Value");
        // 等待一段时间以确保线程池中的线程被重用
        Thread.sleep(1000);



        // 提交第二个任务
        executorService.submit(() -> {
            System.out.println("Task 2 - Thread [" + Thread.currentThread().getName() + "] InheritableThreadLocal Value: " + inheritableThreadLocal.get());
            System.out.println("Task 1 - Thread [" + Thread.currentThread().getName() + "] transmittableThreadLocal Value: " + transmittableThreadLocal.get());

        });

        // 关闭线程池
        executorService.shutdown();
    }
}
